package com.xuxin.baby.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.entity.LocalMedia;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.UploadFilesBean;
import com.xuxin.baby.contract.ChildGreatRecordContract;
import com.xuxin.baby.contract.UploadFilesContract;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.network.Retrofit;
import com.xuxin.baby.photo.PhotoUtils;
import com.xuxin.baby.presenter.ChildGreatRecordPresenter;
import com.xuxin.baby.presenter.UploadFilesPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.PathUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by xu_xin
 * Created on 2020.09.09 0009
 * 记录宝宝大事记
 */
public class ChildGreatRecordActivity extends BaseActivity implements ChildGreatRecordContract.View, UploadFilesContract.View {
    private final ChildGreatRecordContract.Presenter presenter = new ChildGreatRecordPresenter(this);
    private final UploadFilesContract.Presenter presenter2 = new UploadFilesPresenter(this);
    RequestOptions options = new RequestOptions().transform(new CenterCrop(), new RoundedCorners(10));
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.child_great_record_content)
    EditText child_great_record_content;
    @BindView(R.id.child_great_record_image)
    ImageView child_great_record_image;

    private String tenantId;//租户id
    private String token;//授权token
    private String childId;//宝宝ID
    private String eventContent;//内容
    private String picture;//图片
    private boolean detail;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_child_great_record);
    }

    @Override
    public void initView() {
        title_name.setText("宝宝大事记");
        button.setText("保存");
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        childId = aCache.getAsString(BaseConstant.childId);
        detail = getIntent().getBooleanExtra("detail", false);
        if (detail) {
            String dynamicContent = getIntent().getStringExtra("dynamicContent");
            picture = getIntent().getStringExtra("dynamicImage");
            button.setVisibility(View.GONE);
            child_great_record_content.setText(dynamicContent);
            if (!StringUtils.isEmpty(picture)) {
                String image = Retrofit.image_url + picture;
                LogUtils.e("记录宝宝大事记 image = " + image);
                GlideApp.with(context).load(image).placeholder(R.mipmap.img_load).apply(options).into(child_great_record_image);
            }
        }
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left, R.id.child_great_record_image,
            R.id.button})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.child_great_record_image) {
            if (detail) {
                PhotoUtils.browser(context, picture);
            } else {
                PhotoUtils.openPhoto(this, new PhotoUtils.OnResultListener() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        takePhoto(result);
                    }
                });
            }
        } else if (id == R.id.button) {
            eventContent = child_great_record_content.getText().toString();
            if (StringUtils.isEmpty(eventContent)) {
                ToastUtils.showShort("请填写大事记描述");
            } else {
                try {
                    if (null != parts && !parts.isEmpty()) {
                        popup.show();
                        handler.sendEmptyMessage(0);
                    } else {
                        popup.show();
                        handler.sendEmptyMessage(1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismiss();
                }
            }
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                presenter2.uploadFiles(tenantId, token, childId, "Edu_EventChild", "pic1", parts);
            } else if (msg.what == 1) {
                presenter.record(tenantId,
                        token,
                        childId,
                        "basic",
                        null,
                        eventContent,
                        null,
                        null,
                        TimeUtils.getNowString(),
                        picture,
                        null,
                        null);
            }
            return false;
        }
    });

    @Override
    public void onSuccess(BaseBean baseBean) {
        setResult(200);
        finish();
    }


    @Override
    public void onSuccess(UploadFilesBean uploadFilesBean) {
        if (!StringUtils.isEmpty(uploadFilesBean.getResult())) {
            picture = uploadFilesBean.getResult();
        }
        handler.sendEmptyMessage(1);
    }

    private List<MultipartBody.Part> parts;

    public void takePhoto(List<LocalMedia> result) {
        LocalMedia media = result.get(0);
        String path = media.isCompressed() ? media.getCompressPath() : media.getPath();
        GlideApp.with(context).load(path).centerCrop().into(child_great_record_image);
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/jpeg"));
        parts = new ArrayList<>();
        parts.add(MultipartBody.Part.createFormData("files", PathUtils.getImageName(), requestBody));
    }
}